package com.ansion.utils;

import android.content.SharedPreferences;
import android.os.SystemClock;

import com.ansion.log.VLog;

/**
 * 异常场景记录：
 * 1.计算服务器时间不准确，远小于设备时间（设备时间是准的）。
 * 排查GCM上报的时间不准确，故抓日志如下：
 * {
 * "count": 1,
 * "serverTime": "1691836841919",
 * "@timestamp": "2023-08-16T02:07:30.895Z",
 * "kClientLocalTime": "57239692",
 * "errorCode": "9",
 * "localClientTime": "57239692",
 * "useNewServiceTime": "true",
 * "kServerTime": "1691836841919",
 * "getServerTimeMillisecond()": "1691955386368",
 * "name": "kAppDebug",
 * "elapsedRealtime()": "175784141",
 * "time": 1692151637759,
 * "deviceCurrentTimeMillis": "1692108288805"
 * }
 * <p>
 * 推测场景如下：
 * kServerTime                 1691836841919  2023-08-12 18:40:41 关机28小时后启动48小时，再进app
 * kClientLocalTime            57239692        15 小时
 * elapsedRealtime             175784141       48小时
 * getServerTimeMillisecond()  1691955386368  2023-08-14 03:36:26  计算出来是过了 48 -15 = 33 小时，丢掉了28小时的关机时间。
 * deviceCurrentTimeMillis     1692108288805  2023-08-15 22:04:48  实际过了76小时，关机了28小时。
 * 日志时间time                 1692151637759  2023-08-16 10:07:17
 * <p>
 * 故结论为:用户关机后，只要不进入Botim，且设备启动时长大于kClientLocalTime，再进去Botim 就会丢掉关机的时长，导致计算错误。
 */
public class ServerTime {

    private static long localClientTime = 0;
    private static long serverTime = 0;

    public static void initNew() {
        init();
    }

    public static void updateNew(long now, boolean force) {
        update(now, force);
    }

    public static long getServerTimeMillisecond() {
        if (serverTime > 0 && localClientTime > 0) {
            return serverTime
                    + (SystemClock.elapsedRealtime() - localClientTime);
        }

        return System.currentTimeMillis();
    }


    private static void init() {
        long st = CommonPreferenceUtils.getInstance().getLong(".kServerTime", 0);
        long lt = CommonPreferenceUtils.getInstance().getLong(".kClientLocalTime", 0);

        serverTime = 0;
        localClientTime = 0;
        if (st != 0 && lt != 0 && SystemClock.elapsedRealtime() > lt) {
            serverTime = st;
            localClientTime = lt;
        }
    }


    private static void update(long now, boolean force) {
        if (now > getServerTimeMillisecond() || force || serverTime == 0 || localClientTime == 0) {
            serverTime = now;
            localClientTime = SystemClock.elapsedRealtime();
            SharedPreferences.Editor ed = CommonPreferenceUtils.getInstance().getEditor();
            ed.putLong(".kServerTime", serverTime);
            ed.putLong(".kClientLocalTime", localClientTime);
            ed.apply();
        }
    }
}
